export default {
  state: {
    cartGoodsList: []
  },
  actions: {
    addToCart({state, commit}, oneGoods) {
      return new Promise( (resolve, reject) => {
        let goods = state.cartGoodsList.find(item => item.id === oneGoods.id)
        if (goods) {
          let qty = oneGoods.buyQty ? oneGoods.buyQty : 1
          commit('addGoodsQty', {'curGoods': goods, 'buyQty': qty})
          resolve('当前商品增加 ' + qty + ' 个')
        }
        else {
          commit('addGoodsToCart', oneGoods)
          resolve('当前商品加到购物车')
        }
      })
    }
  },
  mutations: {
    addGoodsQty(state, {curGoods, buyQty}) {
      curGoods.buyQty += buyQty
    },
    addGoodsToCart(state, oneGoods) {
      // should set default value, otherwise vue may not watch the change of the value
      if (!oneGoods.buyQty) {
        oneGoods.buyQty = 1
      }
      oneGoods.checked = true

      state.cartGoodsList.push(oneGoods)
    },
    selectAllGoods(state, selected) {
      state.cartGoodsList.forEach(item => { item.checked = selected });
    }
  },
  getters: {
    cartGoodsCount(state, getters){
      return state.cartGoodsList.length
    },
    cartGoodsList(state, getters){
      return state.cartGoodsList
    },
    selGoodsAmount(state, getters){
      let list = state.cartGoodsList.filter(item => item.checked)
      return list.reduce( ((prev, curr) => prev + curr.price * curr.buyQty), 0).toFixed(2)
    },
    selGoodsCount(state, getters){
      return state.cartGoodsList.filter(item => item.checked).length
    },
    allGoodsSelected(state, getters){
      return state.cartGoodsList.length > 0 && !state.cartGoodsList.find(item => !item.checked)
    },
    hasGoodsSelected(state, getters){
      return state.cartGoodsList.find(item => item.checked)
    }
  }
}